﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Web.Caching;
using System.Web;
using ShopzillaV1.Models;
using System.Xml.Serialization;
using System.IO;
using System.Net;

namespace ShopzillaV1.DataAccess
{
    public class ShopzillaHelper
    {

        public const int PageSize = 20;

        public static Cache MyCache
        {
            get
            {
                return HttpRuntime.Cache;
            }
        }

        const string publisherId = "19072";

        const string apiKey = "44c8b8a956abd3c9d6987cc10c910dcf";

        const string allCategoriesRequestUrlFormatString = "http://catalog.bizrate.com/services/catalog/v1/us/taxonomy?apiKey={0}&publisherId={1}&placementId=1&categoryId=&keyword=&ancestors=&results=10&sort=prob_desc";

        //public static XmlNodeList GetAllCategories()
        //{
        //    XmlNodeList result;
        //    string cacheKey = "GetAllCategoriesShopzilla";
        //    result = MyCache[cacheKey] as XmlNodeList;
        //    if (result == null)
        //    {
        //        XmlDocument document = new XmlDocument();
        //        string allCategoriesRequestUrl = string.Format(allCategoriesRequestUrlFormatString, apiKey, publisherId);
        //        using (XmlTextReader reader = new XmlTextReader(allCategoriesRequestUrl))
        //        {
        //            reader.Namespaces = false;
        //            document.Load(reader);
        //        }

        //        result = document.SelectNodes("TaxonomyResponse/Taxonomy/Categories/Category/Children/Category");
        //        MyCache.Add(cacheKey, result, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);
        //    }
        //    return result;
        //}

        public static TaxonomyResponse GetAllCategories()
        {
            TaxonomyResponse result;
            string cacheKey = "GetAllCategoriesShopzilla";
            result = MyCache[cacheKey] as TaxonomyResponse;
            if (result == null)
            {
                XmlDocument document = new XmlDocument();
                string allCategoriesRequestUrl = string.Format(allCategoriesRequestUrlFormatString, apiKey, publisherId);

                XmlSerializer serializer = new XmlSerializer(typeof(TaxonomyResponse));
                using (XmlTextReader reader = new XmlTextReader(allCategoriesRequestUrl))
                {
                    document.Load(reader);
                }
                string answer = document.InnerXml.Replace("xmlns=\"http://www.shopzilla.com/services/catalog\"", "");

                MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(answer));
                result = serializer.Deserialize(ms) as TaxonomyResponse;
                MyCache.Add(cacheKey, result, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            return result;
        }

        //public static List<XNode> GetAllCategories()
        //{
        //    List<XNode> result;
        //    string cacheKey = "GetAllCategoriesShopzilla";
        //    result = MyCache[cacheKey] as List<XNode>;
        //    if (result == null)
        //    {

        //        string allCategoriesRequestUrl = string.Format(allCategoriesRequestUrlFormatString, apiKey, publisherId);

        //        XDocument document = XDocument.Load(allCategoriesRequestUrl);
        //        result = document
        //            .Element("{http://www.shopzilla.com/services/catalog}TaxonomyResponse")
        //            .Element("{http://www.shopzilla.com/services/catalog}Taxonomy")
        //            .Element("{http://www.shopzilla.com/services/catalog}Categories")
        //            .Element("{http://www.shopzilla.com/services/catalog}Category")
        //            .Element("{http://www.shopzilla.com/services/catalog}Children")
        //            .Nodes().ToList();

        //        //result = element.DescendantNodes() as List<XNode>;
        //        //result = ((System.Xml.XmlElement)document.SelectSingleNode("/").FirstChild).FirstChild.FirstChild.FirstChild.LastChild.ChildNodes;
        //        MyCache.Add(cacheKey, result, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);
        //    }
        //    return result;
        //}

        public static ProductResponse GetProductsByCategory(string categoryId, int pageNumber)
        {
            ProductResponse result = null;
            int startIndex = pageNumber * PageSize + 1;
            string cacheKey = "GetProductsByCategory" + categoryId + pageNumber.ToString();
            result = MyCache[cacheKey] as ProductResponse;
            if (result == null)
            {
                XmlDocument document = new XmlDocument();
                string xmlPath = string.Format("http://catalog.bizrate.com/services/catalog/v1/us/product?apiKey={0}&publisherId={1}&placementId=1&categoryId={2}&keyword=&productId=&productIdType=SZPID&merchantId=&minPrice=&maxPrice=&startOffers=0&resultsOffers=3&sort=relevancy_desc&brandId=&attFilter=&showAttributes=&showProductAttributes=&zipCode=&offersOnly=false&biddedOnly=&minRelevancyScore=100&results={3}&start={4}",
               apiKey, publisherId, categoryId, PageSize, startIndex);

                XmlSerializer serializer = new XmlSerializer(typeof(ProductResponse));
                using (XmlTextReader reader = new XmlTextReader(xmlPath))
                {
                    document.Load(reader);
                }
                string answer = document.InnerXml.Replace("xmlns=\"http://www.shopzilla.com/services/catalog\"", "");

                MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(answer));
                result = serializer.Deserialize(ms) as ProductResponse;
                MyCache.Add(cacheKey, result, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            return result;
        }

        public static string GetCategoryNameByCategoryId(string categoryId)
        {
            string result;
            string xmlPath = string.Format("http://catalog.bizrate.com/services/catalog/v1/us/taxonomy?apiKey={0}&publisherId={1}&placementId=1&categoryId={2}&keyword=&ancestors=&results=10&sort=prob_desc",
            apiKey, publisherId, categoryId);
            XmlDocument document;
            document = MyCache[xmlPath] as XmlDocument;
            if (document == null)
            {
                document = new XmlDocument();

                using (XmlTextReader reader = new XmlTextReader(xmlPath))
                {
                    reader.Namespaces = false;
                    document.Load(reader);
                }
                MyCache.Add(xmlPath, document, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            result = document.SelectSingleNode("TaxonomyResponse/Taxonomy/Categories/Category/name").InnerText;
            return result;
        }

        public static List<Category> GetSubCategoriesByCategoryId(string categoryId)
        {
            List<Category> result = null;
            TaxonomyResponse allCats = GetAllCategories();
            var query = allCats.Taxonomy.Categories[0].ChildCategories.Where(a => a.ID == categoryId);
            if (query.Any())
            {
                result = allCats.Taxonomy.Categories[0].ChildCategories.Single(a => a.ID == categoryId).ChildCategories;
            }

            return result;
        }


        public static XmlNodeList GetSubCategories(string id)
        {
            throw new NotImplementedException();
        }

        public static XmlNode GetProductDetails(string id)
        {
            XmlNode result;
            string cacheKey = id;
            result = MyCache[cacheKey] as XmlNode;
            if (result == null)
            {
                XmlDocument document = new XmlDocument();
                string xmlPath = string.Format("http://catalog.bizrate.com/services/catalog/v1/us/product?apiKey=44c8b8a956abd3c9d6987cc10c910dcf&publisherId=19072&placementId=1&categoryId=&keyword=&productId={0}&productIdType=SZPID&merchantId=&minPrice=&maxPrice=&start=0&results=10&startOffers=&resultsOffers=250&sort=relevancy_desc&brandId=&attFilter=&showAttributes=true&showProductAttributes=true&zipCode=&offersOnly=false&biddedOnly=&minRelevancyScore=100", id);
                using (XmlTextReader reader = new XmlTextReader(xmlPath))
                {
                    //reader.Namespaces = false;
                    document.Load(reader);
                }
                string xml = document.OuterXml.Replace(@"xmlns=""http://www.shopzilla.com/services/catalog""", "");
                document.LoadXml(xml);
                result = document.SelectSingleNode("ProductResponse/Products/Product");
                if (result!=null)
                {
                    MyCache.Add(cacheKey, result, null, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High, null);    
                }                
            }
            return result;
        }
    }
}
